//
//  luoerMainTabBar.swift
//  WeiBoStudy
//
//  Created by luoerliu on 16/5/11.
//  Copyright © 2016年 刘文平. All rights reserved.
//

import UIKit

class luoerMainTabBar: UITabBar {
//    加号按钮的闭包属性
    var composeCallback: (() -> ())?
//    调用layoutsubview方法为按钮布局
    override func layoutSubviews() {
        super.layoutSubviews()
//        计算宽度
        let width = self.frame.width/5
//        记录按钮的位置
        var index = 0
//        遍历子控件
        for view  in self.subviews
        {
            if view.isKindOfClass(NSClassFromString("UITabBarButton")!)
            {
                // 重新设置frame
                view.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: self.frame.height)
                index++
                if index == 2 {
                    index++
                }
            }
        }
        // 设置加号按钮的位置
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: self.frame.height)
    }
//    按钮点击事件的实现
    func composeButtonClick(button: UIButton)
    {
        composeCallback?()
    }
    //通过懒加载的方式创建自定义tabbar
    lazy var composeButton:UIButton =
    {
        let button = UIButton(type: UIButtonType.Custom)
//        设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:
            UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState:  UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        self.addSubview(button)
//        为按钮添加点击操作
        button.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
 
}
